﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace LanguageTrans
{
    /// <summary>
    /// 语言转换工具
    /// </summary>
    public class TransUtils
    {
        // APP ID
        public static string appId = string.Empty;
        // 密钥
        public static string secretKey = string.Empty ;
        private static Random rd = new Random();
        static void Main(string[] args)
        {
            
            while(true)
            {
                Console.Write("输入中文本:");
                string str = Console.ReadLine();
                string res = Trans_CN2EN(str);
                Console.WriteLine("翻译:" + res);

                //string s=Console.ReadLine();
                //string res = CNConfuse(s);
                //Console.WriteLine(res);
            }
            
        }

        /// <summary>
        /// 英-》中
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public static string Trans_EN2CN(string q)
        {
            
            // 源语言
            string from = "en";
            // 目标语言
            string to = "zh";
            string retString = TranslationByBaiduTrans(q,from,to,appId,secretKey);
            string res = GetDst(retString);
            return res;
        }
        /// <summary>
        /// 中-》英
        /// </summary>
        /// <param name="q"></param>
        /// <returns></returns>
        public static string Trans_CN2EN(string q)
        {
            // 源语言
            string from = "zh";
            // 目标语言
            string to = "en";           
            string retString = TranslationByBaiduTrans(q, from, to, appId, secretKey);
            string res = GetDst(retString);
            return res;
        }
        /// <summary>
        /// 基于百度翻译api的翻译功能
        /// </summary>
        /// <param name="q">待翻译字符串</param>
        /// <param name="from">源语言</param>
        /// <param name="to">目标语言</param>
        /// <param name="appId"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        private static string TranslationByBaiduTrans(string q,string from,string to,string appId,string secretKey)
        {
            if (appId == string.Empty || secretKey == string.Empty)
            {
                throw new Exception("appId与密钥未设置，请联系管理员~~~");                
            }
            string salt = rd.Next(100000).ToString();
            string sign = EncryptString(appId + q + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(q);
            url += "&from=" + from;
            url += "&to=" + to;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
                return retString;
            }
            catch (Exception ex)
            {
                throw new Exception("网络请求失败"+ex.Message);
            }
            
        }

        /// <summary>
        /// 从josn中获取dst，仅用于处理百度翻译api返回内容
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string GetDst(string str)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                JsonDocument jsonDocument = JsonDocument.Parse(str);
                if (str.Contains("trans_result"))
                {
                    foreach (var item in jsonDocument.RootElement.GetProperty("trans_result").EnumerateArray())
                    {
                        if (item.TryGetProperty("dst", out var dstProperty))
                        {
                            sb.Append(dstProperty.GetString());
                        }
                    }
                }
                else if (str.Contains("error_code"))
                {
                    sb.Append("出现错误！\n");
                    var errorCodeProperty = jsonDocument.RootElement.GetProperty("error_code");
                    sb.AppendLine("错误码：" + errorCodeProperty.GetString());
                    var errorMsgProperty = jsonDocument.RootElement.GetProperty("error_msg");
                    sb.AppendLine("错误信息：" + errorMsgProperty.GetString());
                }
                return sb.ToString();
            }
            catch(Exception ex)
            {
                throw new Exception("JSON解析错误"+ex.Message);
            }            
        }

        /// <summary>
        /// 计算MD5值,仅用于百度翻译api
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串，
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }
        /// <summary>
        /// 中文语序不影响阅读
        /// </summary>
        /// <param name="str"></param>
        /// <param name="coefficent">混乱系数</param>
        /// <returns></returns>
        public static string CNConfuse(string str,int coefficent=20)
        {
            Regex reg = new Regex("[^一-﨩]{1,}");
            MatchCollection signs =reg.Matches(str);
            string[]strs=reg.Split(str);
            List<string>strlist=strs.ToList();
            StringBuilder sb=new StringBuilder();
            for(int i = 0; i < strs.Length; i++)
            {
                string r = ChineseCharactersConfuse(strs[i],coefficent);
                sb.Append(r);
                if (i < signs.Count)
                {
                    sb.Append(signs[i]);
                }
            }
            
            return sb.ToString();
        }
        /// <summary>
        /// 无间隔符号的中文字符串乱序处理
        /// </summary>
        /// <param name="s"></param>
        /// <param name="coefficent">混乱系数</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private static string ChineseCharactersConfuse(string s, int coefficent)
        {
            char[] charArray = s.ToCharArray();
            if (s.Length<=1)return s;
            else if (s.Length == 2)
            {
                char tmp = charArray[0];
                charArray[0] = charArray[1];
                charArray[1] = tmp;
            }
            else
            {
                Random rand = new Random();
                for (int i = 0; i < coefficent; i++)
                {
                    int j = rand.Next(1, s.Length - 1);
                    char temp = charArray[j];
                    charArray[j] = charArray[j+1];
                    charArray[j+1] = temp;
                }
            }
            
            return new string(charArray);
        }
    }
}
